// 主页
import React, {useEffect, useState} from 'react';
import {View, Text, StyleSheet, Image, PixelRatio} from 'react-native';
import {IUserInfo} from '@/models/user';
import {connect, ConnectedProps} from 'react-redux';
import {RootState} from '@/models/index';
import Touchable from '../../components/Touchable';
import AsyncStorage from '@react-native-async-storage/async-storage';
const mapStateToProps = ({users}: RootState) => {
  return {
    photographerInfo: users?.userInfo,
  };
};
const connector = connect(mapStateToProps);
type ModelState = ConnectedProps<typeof connector>;
interface IProps extends ModelState {
  navigation: {navigate: any};
  // route: {params: {selectedId: string}};
  route: any;
}
function PrincipalSheet(props: IProps) {
  const {navigation, route, photographerInfo,dispatch} = props;
  const [item, setItem] = useState<IUserInfo[]>();
  const [clickLink, setClickLink] = useState<boolean>(false);
  useEffect(() => {
    // 根据传过来的selectedId选出选中项
    const selectedItem = photographerInfo?.filter(item => {
      console.log("selectedId",route.params.selectedId)
      return item._id === route.params.selectedId;
    });
    console.log("selectedItem",selectedItem)
    setItem(selectedItem);
  }, []);
  const handleEnterActive = () => {
    setClickLink(true);
    navigation.navigate('Active');
    setClickLink(false);
  };
  const handleChat = async() => {
    // 跳转到聊天页面时首先该用户应该是登录状态
    // 获取token，如果当前的token存在，那么代表用户已经登录了，可以访问chat页面
    console.log("获取到了token",await AsyncStorage.getItem('token'))
    // token必须是异步的获取
    const token = await AsyncStorage.getItem('token');
    // let isLogin = false;
    if (token) {
      // 点击跳转到聊天页面
      // navigation.navigate('Login');
      // 跳转时得把当前主页用户的信息的id传递过来
      navigation.navigate('Chat',{
        selectedId:route.params.selectedId
      });
    } else {
      navigation.navigate('Login');
      // navigation.navigate('Chat');
    }
  };
  return (
    <View style={styles.principalSheet}>
      {item && item[0] &&(
        <View style={styles.top}>
          <Image source={{uri: item[0].scurpture}} style={styles.image}></Image>
          <View>
            <Text style={styles.text}>用户名：{item[0].username}</Text>
            <Text style={styles.text}>年龄：{item[0].age}</Text>
            <Text style={styles.text}>性格：{item[0].nature}</Text>
            <Text style={styles.text}>距离我：</Text>
            <Text style={styles.text}>身份：{item[0].identity}</Text>
            <Text style={styles.text}>常住城市：{item[0].city}</Text>
          </View>
        </View>
      )}
      <View>
        <Text
          style={clickLink ? styles.link : styles.unlink}
          onPress={handleEnterActive}>
          进入他（她）的动态：》》》
        </Text>
      </View>
      <View style={styles.bottom}>
        <View>
          <Text style={styles.title}>作品</Text>
        </View>
        <View style={styles.photo}>
          {item && item[0] && 
            item[0].works?.map((work, index) => {
              return (
                <Image
                  key={work.work_id}
                  source={{uri: work.work_url}}
                  style={styles.workImage}></Image>
              );
            })}
        </View>
      </View>
      <Touchable style={styles.btnBox} onPress={handleChat}>
        <Text style={styles.btn}>联系他（她）</Text>
      </Touchable>
    </View>
  );
}
const styles = StyleSheet.create({
  principalSheet: {
    padding: 20,
    display: 'flex',
    flexDirection: 'column',
  },
  top: {
    paddingBottom: 30,
    height: 160,
    diaplay: 'flex',
    flexDirection: 'row',
    fontSize: 40,
  },
  bottom: {
    marginVertical: 20,
  },
  image: {
    width: 120,
    height: 120,
    borderRadius: 120,
    marginHorizontal: 20,
  },
  text: {
    fontSize: 16,
  },
  unlink: {
    fontSize: 16,
    color: '#A75E5E',
  },
  link: {
    fontSize: 16,
    color: 'red',
  },
  title: {
    fontSize: 18,
    fontWeight: '700',
    marginBottom: 20,
  },
  photo: {
    width:"100%",
    display: 'flex',
    flexDirection: 'row',
    flexWrap: 'wrap',
  },
  workImage: {
    width: 102,
    height: 102,
    marginHorizontal:2,
    marginVertical:2,
  },
  btnBox: {
    marginVertical: 30,
    width: 200,
    height: 50,
    borderRadius: 50,
    backgroundColor: '#A75E5E',
    alignSelf: 'center',
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
  },
  btn: {
    fontSize: 16,
    color: '#fff',
    fontWeight: '700',
  },
});
export default connector(PrincipalSheet);
